package com.lzb.provide;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText et_id;
    private EditText et_message;
    private ContentResolver contentResolver;
    public static final String TAG = MainActivity.class.getSimpleName();

    private Uri uri;
    private Handler  handler  = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x123){
                if (uri != null){
                    Cursor cursor  = contentResolver.query(uri,null,null,null,null);
                    if (null != cursor){
                        cursor.moveToNext();
                        int id = cursor.getInt(cursor.getColumnIndex(SQLiteOpenHelperUtil.STUDENT_ID));
                        String message = cursor.getString(cursor.getColumnIndex(SQLiteOpenHelperUtil.MESSAGE));
                        Toast.makeText(MainActivity.this, ("ID=" + id + " ; message=" + message), Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(MainActivity.this, "数据发生变化", Toast.LENGTH_SHORT).show();
                }
            }
            return false;
        }
    });

    /** 内容提供者监听类 */
    private ContentObserver contentObserver = new ContentObserver(handler) {
        @Override
        public boolean deliverSelfNotifications() {
            Log.i(TAG ,"deliverSelfNotifications");
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.i(TAG ,"onChange-------->");
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            Log.i(TAG ,"onChange-------->" + uri);
            handler.sendEmptyMessage(0x123);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_id = (EditText) findViewById(R.id.et_id);
        et_message = (EditText) findViewById(R.id.et_message);
        //动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE},0x234);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        contentResolver = getContentResolver();
        /**
         * 参数：
         * 一 uri：该监听器所要监听的ContentProvide的uri
         * 二 notifyForDescendants：假设注册监听的Uri为 content://abc  notifyForDescendants为 true
         *                          那么Uri为content://abc/lzb、 content://abc/xxx的数据发生变化时，
         *                          也能触发监听器，否则不能触发监听器
         * 三 observer：监听器实例
         */
        contentResolver.registerContentObserver(MyContentProvide.CONTENT_URI, true, contentObserver);
    }

    /**
     * 添加数据
     */
    public void add(View view){
        if (TextUtils.isEmpty(et_id.getText().toString()) || TextUtils.isEmpty(et_message.getText().toString())){
            Toast.makeText(this, "请填数据", Toast.LENGTH_SHORT).show();
            return;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(SQLiteOpenHelperUtil.STUDENT_ID,Integer.valueOf(et_id.getText().toString().trim()));
        contentValues.put(SQLiteOpenHelperUtil.MESSAGE,et_message.getText().toString());
        uri = contentResolver.insert(MyContentProvide.CONTENT_URI,contentValues);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x234 ){//应用没有被授权关闭应用
            if (grantResults[0] != 0 || grantResults[1] != 0){
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        contentResolver.unregisterContentObserver(contentObserver);
    }
}
